var express = require('express');
var router = express.Router();
//导入jwt
const jwt = require('jsonwebtoken');

//声明中间件
const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware');

//读取配置项
const { secret, expiresIn } = require('../../config/config');

const UserModel = require('../../models/UserModel');
const md5 = require('md5');



//登录操作
router.post('/login', (req, res) => {
    let { username, password } = req.body

    //查询数据库
    UserModel.findOne({ username: username, password: md5(password) }).then((data) => {
        if (!data) {
            return res.json({
                code: '2002',
                msg: '用户名或密码错误',
                data: null
            });
        } else {
            //登录成功
            //创建当前用户的token
            let token = jwt.sign({
                username: data.username,
                _id: data._id
            }, secret, {
                expiresIn: expiresIn
            });

            //计算exp
            let exp = (new Date().getTime() / 1000) + expiresIn;
            //更新用户的exp
            // 创建更新对象
            const update = {
                $set: {
                    exp: exp
                }
            };
            UserModel.findByIdAndUpdate(data._id, update, { new: true }).then(() => { }).catch((err) => {
                return res.json({
                    code: '2007',
                    msg: '更新用户过期时间出错',
                    data: null
                });
            });

            //响应token
            return res.json({
                code: '0000',
                msg: '登录成功',
                data: token
            });
        }
    }).catch((err) => {
        res.json({
            code: '2001',
            msg: '数据库读取失败',
            data: null
        });
    });
});

//退出登录
router.post('/logout', checkTokenMiddleware, (req, res) => {

    // let {_id} = jwt.decode(req.get('token'));
    let {_id} = req.user;

    //设置用户过期时间
    //更新用户的exp
    //计算exp
    let exp = (new Date().getTime() / 1000);
    // 创建更新对象
    const update = {
        $set: {
            exp: exp
        }
    }
    UserModel.findByIdAndUpdate(_id, update, { new: true }).then((data) => {
        return res.json({
            code: '0000',
            msg: '退出成功',
            data: null
        });

    }).catch((err) => {
        return res.json({
            code: '2008',
            msg: '更新用户过期时间出错',
            data: null
        });
    });


    // //销毁session
    // req.session.destroy(()=>{
    //     res.render('success', {msg: '退出成功', url: '/login'});
    // })

});


module.exports = router;
